<?php
namespace app\common\model;

use think\Model;
use app\Request;
use think\Validate;
use think\exception\ValidateException;

class Base extends Model
{
	protected $pk = 'id';
	protected $autoWriteTimestamp = true;
	protected $type       = [
        'create_time' => 'timestamp:Y-m-d H:i:s',
        'update_time' => 'timestamp:Y-m-d H:i:s',
    ];
    protected $createTime='create_time';
    protected $updateTime='update_time';

    /**
     * 获取列表
     * 参数类型参照thinkphp默认的方法
     * @return array 列表
     */
    public function loadList($option = []){

        try{
            $model = $this;
            if (!empty($option['withTrashed'])){
                $model = $model->withTrashed();
            }
            if (!empty($option['onlyTrashed'])){
                $model = $model->onlyTrashed();
            }
            if (!empty($option['with'])){
                $model = $model->with($option['with']);
            }
            if (!empty($option['field'])){
                $model = $model->field($option['field']);
            }
            if (!empty($option['where'])){
                $model = $model->where($option['where']);
            }
            if (!empty($option['whereOr'])){
                $model = $model->whereOr($option['whereOr']);
            }
            if (!empty($option['whereColumn'])){
//                [
//                    ['update_time', '>', 'create_time'],
//                    ['name', '=', 'nickname']
//                ]
                foreach ($option['whereColumn'] as $column) {
                    $model = $model->whereColumn(...$column);
                }
            }

            if (!empty($option['whereTime'])){
//                [
//                    ['birthday', '>=', '1970-10-1'],
//                    ['birthday', 'between', ['1970-10-1', '2000-10-1']]
//                ]
                foreach ($option['whereTime'] as $column) {
                    $model = $model->whereTime(...$column);
                }
            }
            if (!empty($option['whereBetweenTime'])){
                foreach ($option['whereBetweenTime'] as $column) {
                    $model = $model->whereBetweenTime(...$column);
                }
            }
            if (!empty($option['whereNotBetweenTime'])){
                foreach ($option['whereNotBetweenTime'] as $column) {
                    $model = $model->whereNotBetweenTime(...$column);
                }
            }
            if (!empty($option['whereYear'])){
//                [
//                    ['create_time','last year']
//                ]
                if (is_array($option['whereYear'])){
                    foreach ($option['whereYear'] as $column) {
                        $model = $model->whereYear(...$column);
                    }
                }else{
                    $model = $model->whereYear($option['whereYear']);
                }
            }
            if (!empty($option['whereMonth'])){
                if (is_array($option['whereMonth'])){
                    foreach ($option['whereMonth'] as $column) {
                        $model = $model->whereMonth(...$column);
                    }
                }else{
                    $model = $model->whereMonth($option['whereMonth']);
                }
            }
            if (!empty($option['whereWeek'])){
                if (is_array($option['whereWeek'])){
                    foreach ($option['whereWeek'] as $column) {
                        $model = $model->whereWeek(...$column);
                    }
                }else{
                    $model = $model->whereWeek($option['whereWeek']);
                }
            }
            if (!empty($option['whereDay'])){
                if (is_array($option['whereDay'])){
                    foreach ($option['whereDay'] as $column) {
                        $model = $model->whereDay(...$column);
                    }
                }else{
                    $model = $model->whereDay($option['whereDay']);
                }
            }

            empty($option['order']) && $option['order'] = $this->pk.' desc';
            $model = $model->order($option['order']);

            if (isset($option['page']) && $option['page'] == false){
                $list = $model->select()->toArray();
                $result = [
                    'result' => 'success',
                    'list' => $list,
                ];
                return $result;
            }else{
                $limit = (new Request())->getParams()['args']['limit'] ?? 20;
                $lists = $model->paginate($limit);
                if (!empty($option['visible'])){
                    $lists = $lists->visible($option['visible']);
                }
                $list = $lists->toArray();
                $page = $lists->render();
            }

            $result = [
                'result' => 'success',
                'list' => $list['data'],
                'pagetpl' => $page?$page:'',
                'page'=>[
                    'per_page' => $list['per_page'],
                    'current_page' => $list['current_page'],
                    'last_page' => $list['last_page'],
                    'total' => $list['total']
                ]
            ];
        }catch(\Exception $e){
            $result = [
                'result' => 'error',
                'msg' => $e->getMessage(),
            ];
        }

        return $result;
    }

    /**
     * 新增数据
     * @param array $data
     * @param string $validate
     * @param string $scene
     * @return array
     */
    public function createData($data = [], $validate = '', $scene = ''): array
    {
        $model = $this;
        if ($validate instanceof Validate){
            try {
                if (!empty($scene)){
                    $validate->scene($scene);
                }
                $result = $validate->failException(true)->check($data);
//                if(!$result){
//                    return $validateClass->getError();
//                }

            } catch (\Exception $e) {
                // 验证失败 输出错误信息
                return ['code' => 0,'msg' => $e->getMessage()];
            }
        }
        $res = $model->create($data);
        if ($res){
            return ['code' => 1,'msg' => lang('add success')];
        }else{
            return ['code' => 0,'msg' => lang('add fail')];
        }

    }
    /**
     * 更新数据
     * @param array $data
     * @param string $validate
     * @param string $scene
     * @return array
     */
    public function modifyData($data = [], $validate = '', $scene = ''): array
    {
        $model = $this;
        if (!isset($data[$this->pk]) || empty($data[$this->pk])){
            return ['result' => 'error','msg' => '缺少更新的条件'];
        }
        if ($validate instanceof Validate){
            try {
                if (!empty($scene)){
                    $validate->scene($scene);
                }
                $result = $validate->failException(true)->check($data);
//                if(!$result){
//                    return $validateClass->getError();
//                }

            } catch (\Exception $e) {
                // 验证失败 输出错误信息
                return ['code' => 0,'msg' => $e->getMessage()];
            }
        }
        $res = $model->update($data);
        if ($res !== false){
            return ['code' => 1,'msg' => lang('edit success')];
        }else{
            return ['code' => 0,'msg' => lang('edit fail')];
        }

    }

}
